/**
 * Created with JetBrains WebStorm.
 * User: rendong
 * Date: 12-8-27
 * Time: 下午9:02
 * :$
 */

window.requestAnimationFrame = function (){
    return window.requestAnimationFrame
        || window.mozRequestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.msRequestAnimationFrame
        || window.oRequestAnimationFrame
        || function(callback) {
        setTimeout(callback, 1000 / 60);
    }
}();

function gStage() {
    // empty
}

/**
 *
 * @type {CanvasRenderingContext2D}
 */
gStage.prototype.context = null;
gStage.prototype.canvas = null;
gStage.prototype.width = 0;
gStage.prototype.height = 0;
gStage.prototype.frameRate = null;
gStage.prototype.frame = 0;
gStage.prototype.time = 0;

gStage.prototype.childs = [];


/**
 * 初始化cavas
 * @param cavas {CanvasRenderingContext2D}
 */
gStage.prototype.init = function (canvas, width, height, frameRate, bgcolor) {
    if (this.canvas != null){
        this.log("only init once!");
        return;
    }

    this.canvas = canvas;
    this.context = canvas.getContext("2d");
    this.width = width;
    this.height = height;
    this.frameRate = frameRate;

    if (bgcolor != undefined){
        this.context.fillStyle=bgcolor;
        this.context.fillRect(0,0,width,height);
    }

    // start render
    var obj = this;
    var i = 0;
    var step = parseInt(60 / frameRate);
    function doRender(timestamp){
        i++;

        if (i % step == 0)// 30帧的速度
            obj.render();

        requestAnimationFrame(doRender);
    }

    this.log("canvas init ",width,":", height);

    doRender(0);
}

gStage.prototype.addChild = function(dispObject)
{
    dispObject.stage = this;
    this.childs.push(dispObject);
}


/**
 * 主渲染方法
 */
gStage.prototype.render = function()
{
    this.frame++;

    var now = new Date().getTime();
    var diff = (now - this.time);
    this.time = now;
    var frameRate = parseInt(1000 / diff);

    var len = this.childs.length;

    this.context.clearRect(0,0, this.width, this.height);
    for(var i=0; i< len; i++){
        var obj = this.childs[i];
        obj.render();
    }

    this.context.font = "25px serif"
    this.context.fillStyle = "#FF0000";
    this.context.fillText ("FPS:" + frameRate,0, 25);
}

/**
 * 根据id获取对象
 * @param id
 * @return {Element}
 */
gStage.prototype.$ = function (id) {
    return document.getElementById(id);
}


/**
 * 日志处理函数
 */
gStage.prototype.log = function () {
    var str = "";
    for (var i = 0; i < arguments.length; i++)
        str += arguments[i];

    if (typeof gdebug != undefined)
        gdebug(str);
    else
        console.log(str);
}

